<template>
  <div ref="draggable" v-show="showCall" style="
      z-index: 9999;
      left: 40px;
      top: 50px;
      width: 800px;
      height: 600px;
      position: absolute;
      background: #ffffff;
      padding: 20px 10px;
      cursor: move;
      box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
    " @mousedown="dragMouseDown">
    <!-- 拖拽视图 -->
    <div class="resize-handle bottom-right" @mousedown.stop="resizeMouseDown('bottom-right', $event)"></div>
    <div class="resize-handle bottom-left" @mousedown.stop="resizeMouseDown('bottom-left', $event)"></div>
    <div class="resize-handle top-right" @mousedown.stop="resizeMouseDown('top-right', $event)"></div>
    <div class="resize-handle top-left" @mousedown.stop="resizeMouseDown('top-left', $event)"></div>

    <div class="modal-content incoming-call-dialog" v-show="callshowModel" style="background: #3c3667; padding: 20px; height: 100%">
      <div class="usr-info">
        <img class="usr-pho" :src="callerPhoto" alt="Caller Photo" />
        <p class="usr-name" style="color: #ffffff">{{ callerName }}</p>
        <p class="incoming-call-tip" style="color: #ffffff">邀请您通话</p>
      </div>
      <div class="op-btns">
        <div class="incoming-call-reject">
          <img @click="rejectCall" src="https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661433175110/reject.png" alt="Reject Call"/>
          <p class="op-txt" style="color: #ffffff">挂断</p>
        </div>
        <div class="incoming-call-video">
          <img @click="answerCall(0)" src="https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661433226356/videoCall.png" alt="Video Call"/>
          <p class="op-txt" style="color: #ffffff">视频通话</p>
        </div>
        <div class="incoming-call-audio">
          <img @click="answerCall(1)" src="https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661433255465/audioCall.png" alt="Audio Call"/>
          <p class="op-txt" style="color: #ffffff">语音通话</p>
        </div>
      </div>
    </div>

    <div id="call-view" style="padding: 20px 0" v-show="callView">
      <div :class="['peer-view', peerViewClass]" @click="switchToMainView('peer')">
        <video id="video-peer" autoPlay v-show="videoPeerShow" ref="videoPeer"></video>
        <audio id="audio-peer" autoPlay v-show="audioPeerShow" ref="audioPeer"></audio>
        <div class="audio-tip-wrap" v-show="audioTip">
          <p class="audio-call">语音通话中</p>
        </div>
      </div>
      <div :class="['local-view', localViewClass]" @click="switchToMainView('local')">
        <video id="video-local" autoPlay ref="videoLocal" v-show="videoLocalShow"></video>
        <audio id="audio-local" autoPlay ref="audioLocal"></audio>
        <div class="audio-tip-wrap" v-show="audioTip">
          <p class="audio-name online-ellipsis">本机</p>
          <p class="audio-call">语音通话中</p>
        </div>
      </div>
      <div class="op-btns" style="position: absolute; bottom: 100px">
        <div class="mute-change-btn" @click="changeMute">
          <img :src="muteUrl" />
          <p class="a-mute">{{ muteText }}</p>
        </div>
        <div class="mode-change-btn" @click="changeMode">
          <img :src="videoCallUrl" />
          <p class="v-mode">{{ videoCallText }}</p>
        </div>
        <div @click="dropCall">
          <img src="https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661433175110/reject.png"/>
          <p style="color: #e24940">挂断</p>
        </div>
      </div>
    </div>
    <audio id="ring-music" loop ref="audioPlayer">
      <source src="https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-9/1662024495462/ring_new.mp3" type="audio/mpeg"/>
    </audio>
    <div class="alert alert-warning fade in" v-if="showText" id="message-alert" style="
        text-align: center;
        padding: 20px;
        background: #3c3667;
        color: #ffffff;
      ">
      <a href="#" class="close" data-dismiss="alert"> &times; </a>
      <span class="call-message">呼叫超时，请稍后再试</span>
    </div>
  </div>
</template>
<script setup name="callDialog">
  import "./index";
  import { ref } from "vue";
  import { callRecordSave, callRecordUpdate, getTokenDueros, getHomeBedApplyId, isAgent, getDeviceInfo } from "@/api/smartSpeaker/index";
  import moment from "moment";

  const height = ref("500px");
  const duerRtcSdk = window.DUER_rtcsdk;
  /*const {homeBedApplyId, homeBedApplyName, imei} = defineProps([
    "homeBedApplyId",
    "homeBedApplyName",
    "imei",
  ]);*/
  const callMode = ref(duerRtcSdk.CallMode.AUDIO_VIDEO);
  const textMode = ref(duerRtcSdk.CallMode.AUDIO_VIDEO);
  const enbaleRtcDebugLog = true;
  const duerRtc = ref(null);
  const showText = ref(false);
  const callView = ref(false);
  const callshowModel = ref(true);
  const showCall = ref(false);
  const callInfo = ref({
    mute: false,
    mode: duerRtcSdk.CallMode.AUDIO_VIDEO,
  });
  const form = ref({});
  const callRecordDTO = ref({
    id: null,
    homeBedApplyId: null,
    homeBedApplyName: null,
    callType: 1,
    callTime: null,
    callStatus: null,
    imei: null,
  });
  // duerRtcSdk.CallMode.AUDIO_VIDEO 0 视频  duerRtcSdk.CallMode.AUDIO_ONLY 1 语音
  const audioPlayer = ref(null);
  const callerName = ref("未知来电");
  const callerPhoto =
      "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-7/1658388218664/pho.png";
  const peerName = ref("被叫名字");
  const peerPhoto = ref(
      "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-7/1658388218664/pho.png",
  );

  const videoCallIcon = ref(
      "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661433226356/videoCall.png",
  );
  const audioCallIcon = ref(
      "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661515364706/audio000.png",
  );

  const muteUrl = ref(
      "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661515279806/quite0.png",
  );
  const muteText = ref("静音");
  const videoCallUrl = ref(
      "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661433226356/videoCall.png",
  );
  const videoCallText = ref("视频通话");
  const audioTip = ref(false);
  const videoPeer = ref(null);
  const audioPeer = ref(null);
  const videoPeerShow = ref(true);
  const audioPeerShow = ref(true);
  const videoLocal = ref(null);
  const audioLocal = ref(null);
  const videoLocalShow = ref(true);
  const token = ref('');

  const peerViewClass = ref("main-view");
  const localViewClass = ref("sub-view");

  const draggable = ref(null);
  let pos1 = 0,
      pos2 = 0,
      pos3 = 0,
      pos4 = 0;

  let callId = ref(null);
  let answerCallTime = ref("");

  let homeBedApplyId = ref(null);
  let homeBedApplyName = ref("");
  let imei = ref("");

  function init(callParams) {
    console.log("【 管理员呼叫 】 = ", callParams);

    homeBedApplyId.value  = callParams.homeBedApplyId;
    homeBedApplyName.value      = callParams.homeBedApplyName;
    imei.value            = callParams.imei;

    console.log("【 homeBedApplyId 】 = ", homeBedApplyId.value);
    console.log("【 homeBedApplyName 】 = ", homeBedApplyName.value);
    console.log("【 imei 】 = ", imei.value);

    console.log("【 当前环境 = 】", process.env.NODE_ENV);
    callshowModel.value = false;
    callView.value = true;
    // showCall.value = true;
    if(process.env.NODE_ENV != "development") {
      deviceInfo();
    } else {
      makeCall("a91b7a09", "100599667273@HARD", duerRtcSdk.CallMode.AUDIO_VIDEO);
    }

    // 生成通话记录
    callRecordDTO.value.homeBedApplyId = homeBedApplyId;
    callRecordDTO.value.homeBedApplyName = homeBedApplyName;
    callRecordDTO.value.callTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    callRecordDTO.value.callType = 1; // 呼出
    callRecordDTO.value.callStatus = 0; // 未接通
    callRecordDTO.value.imei = imei; // 设备序列号

    // 发送请求
    callSave(callRecordDTO.value);
  }

  /**
   * 获取设备呼叫需要的参数
   */
  function deviceInfo() {
    getDeviceInfo(imei.value).then(res => {
      if(res.code != 0) {
        proxy.$modal.msgError("服务器内部错误");
      } else {
        makeCall(res.deviceInfo.callAppid, res.deviceInfo.callAddress, duerRtcSdk.CallMode.AUDIO_VIDEO);
      }
    })
  }

  const switchToMainView = (view) => {
    if (view === "peer" && peerViewClass.value !== "main-view") {
      peerViewClass.value = "main-view";
      localViewClass.value = "sub-view";
    } else if (view === "local" && localViewClass.value !== "main-view") {
      localViewClass.value = "main-view";
      peerViewClass.value = "sub-view";
    }
  };

  const dragMouseDown = (e) => {
    e.preventDefault();
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }

  const elementDrag = (e) => {
    e.preventDefault();
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    if (draggable.value) {
      draggable.value.style.top = draggable.value.offsetTop - pos2 + "px";
      draggable.value.style.left = draggable.value.offsetLeft - pos1 + "px";
    }
  };

  const closeDragElement = () => {
    document.onmouseup = null;
    document.onmousemove = null;
  }

  const closeResizeElement = () => {
    document.onmouseup = null;
    document.onmousemove = null;
  }

  const resizeMouseDown = (corner, e) => {
    e.preventDefault();
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeResizeElement;
    document.onmousemove = (event) => elementResize(event, corner);
  }

  const elementResize = (e, corner) => {
    e.preventDefault();
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;

    if (draggable.value) {
      const el = draggable.value;
      switch (corner) {
        case "bottom-right":
          el.style.width = el.offsetWidth - pos1 + "px";
          el.style.height = el.offsetHeight - pos2 + "px";
          break;
        case 'bottom-left':
          el.style.width = el.offsetWidth + pos1 + "px";
          el.style.height = el.offsetHeight - pos2 + "px";
          el.style.left = el.offsetLeft - pos1 + "px";
          break
        case 'top-right':
          el.style.width = el.offsetWidth - pos1 + "px";
          el.style.height = el.offsetHeight + pos2 + "px";
          el.style.top = el.offsetTop - pos2 + "px";
          break;
        case 'top-left':
          el.style.width = el.offsetWidth + pos1 + "px";
          el.style.height = el.offsetHeight + pos2 + "px";
          el.style.left = el.offsetLeft - pos1 + "px";
          el.style.top = el.offsetTop - pos2 + "px";
          break;
      }
    }
  };

  // 小度智能屏终端呼叫: 展示接听窗口
  function incomingViewShow() {
    showCall.value = true;
    callshowModel.value = true;
    if (audioPlayer.value) {
      audioPlayer.value.play();
    }
  }

  function ringViewShow() {
    if (audioPlayer.value) {
      audioPlayer.value.play();
    }
    peerName.value = "小度";
    if (callInfo.value.callMode == duerRtcSdk.CallMode.AUDIO_VIDEO) {
      // 当前为视频通话
      textMode.value = duerRtcSdk.CallMode.AUDIO_ONLY;
      // videoCallIcon.value =
      ("https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661515364706/audio000.png");
    } else if (callInfo.value.callMode == duerRtcSdk.CallMode.AUDIO_ONLY) {
      audioCallIcon.value =
          "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661828922567/videoCall0.png";
    }
    textMode.value = duerRtcSdk.CallMode.AUDIO_VIDEO;
  }

  function freeCallView() {
    console.log("【 Invoke free Call method ... 】")
    if (audioPlayer.value) {
      audioPlayer.value.pause();
    }
    Object.assign(callInfo, {
      mute: false,
    });
    callView.value = false;
    callshowModel.value = false;
    showCall.value = false;
    if (form.value.callStatus == 1) {
      form.value.endCallTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      form.value.duration = calculateTimeDifference(
          form.value.answerCallTime,
          form.value.endCallTime,
      )
    }
    emit("hideDialog");
    // callSave(form.value)
  }

  function callTimeout() {
    showText.value = true;
    callView.value = false;
    callshowModel.value = true;
    showCall.value = false;
    // callSave(form.value);
  }
  function changeMute() {
    if (callInfo.value.mute) {
      muteUrl.value =
          "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661515279806/quite0.png";
      muteText.value = "静音";
    } else {
      muteUrl.value =
          "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661515279209/quite.png";
      muteText.value = "已静音";
    }
    callInfo.value.mute = !callInfo.value.mute;
    duerRtc.value.muteAudio(callInfo.value.mute);
  }

  /**
   * 显示呼叫视图
   */
  function callViewShow() {
    console.log("【 小度智能屏正常接听 】")

    if (audioPlayer.value) {
      audioPlayer.value.pause();
    }
    if (callInfo.value.mute) {
      // 已静音
      muteUrl.value =
          "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661515279209/quite.png";
      muteText.value = "已静音";
    } else {
      muteUrl.value =
          "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661515279806/quite0.png";
      muteText.value = "静音";
    }
    if (callInfo.value.callMode == duerRtcSdk.CallMode.AUDIO_VIDEO) {
      // 当前为视频通话
      videoCallUrl.value =
          "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661515364706/audio000.png";
      videoCallText.value = "语音通话";
      audioTip.value = false;
    } else if (callInfo.value.callMode == duerRtcSdk.CallMode.AUDIO_ONLY) {
      videoCallUrl.value =
          "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661828922567/videoCall0.png";
      videoCallText.value = "视频通话";
      audioTip.value = true;
    }

    callView.value = true;
    callshowModel.value = false;

    // 保存通话记录:记录开始时间
    callRecordDTO.value.id = callId.value;
    callRecordDTO.value.homeBedApplyId = 63;
    callRecordDTO.value.homeBedApplyName = "严小香";
    callRecordDTO.value.callType = 1;
    callRecordDTO.value.callStatus = 0;
    answerCallTime.value = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    callRecordDTO.value.answerCallTime = answerCallTime.value;
    callRecordDTO.value.imei = imei.value;

    console.log("【 管理员呼叫更新记录请求 】 = ", callRecordDTO.value);

    // 更新通话记录
    callRecordUpdateAPI(callRecordDTO.value);

    // $('#call-view').show();
  }
  function setLayouts(layouts) {
    if (!layouts) {
      return;
    }

    const [layoutLocal, layoutPeer] = layouts;

    if (layoutLocal.videoTrack) {
      videoLocalShow.value = true;
      audioTip.value = false;
      const stream = new MediaStream();
      stream.addTrack(layoutLocal.videoTrack);
      videoLocal.value.srcObject = stream;
    } else {
      videoLocalShow.value = false;
      audioTip.value = true;
    }
    if (layoutLocal.audioTrack && !layoutLocal.isLocal) {
      const stream = new MediaStream();
      stream.addTrack(layoutLocal.audioTrack);
      audioLocal.value.srcObject = stream;
    }

    if (layoutPeer.videoTrack) {
      videoPeerShow.value = true;
      audioTip.value = false;
      const stream = new MediaStream();
      stream.addTrack(layoutPeer.videoTrack);
      videoPeer.value.srcObject = stream;
    } else {
      videoPeerShow.value = false;
      audioTip.value = true;
    }
    if (layoutPeer.audioTrack) {
      const stream = new MediaStream();
      stream.addTrack(layoutPeer.audioTrack);
      audioPeer.value.srcObject = stream;
    }
  }

  /**
   * rtc监听器
   * @param loginParams
   */
  const rtcListener = (loginParams) => {
    duerRtc.value = new duerRtcSdk.RtcContext(
        {
          onAuthStatusChanged: (auth) => {
            if (auth.success) {
              console.log("auth.success");
              // 自动或手动入席离席只能二选一，不能混用！！！
              // 开启自动入席离席
              // duerRtc.value.enableCustomer(true);
              // 开启手动入席离席
              const customer = duerRtc.value.enableCustomer(false);
              customer.join();
              // this.setState({ isLogin: true })
            } else {
              switch (auth.code) {
                case duerRtcSdk.AuthCode.PARAM_ERROR:
                case duerRtcSdk.AuthCode.APPID_INVALID: {
                  // 联调阶段可能遇到的错误
                  break
                }
                case duerRtcSdk.AuthCode.TOKEN_INVALID:
                case duerRtcSdk.AuthCode.TOKEN_EXPIRED: {
                  // 重新刷新token
                  break;
                }
                case duerRtcSdk.AuthCode.NO_ERROR:
                case duerRtcSdk.AuthCode.OTHER_DEVICE_LOGIN: {
                  break;
                }
              }
            }
          },
        },
        enbaleRtcDebugLog,
    );

    // 设置呼叫(被动)监听器
    duerRtc.value.setCallListener({
      onIncomingCall: (intent) => {
        console.log("【 呼叫接通 】 = ", intent);

        // 保存通话记录
        callRecordDTO.value.callType = 0;
        callRecordDTO.value.callStatus = 0;
        callRecordDTO.value.callTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
        callRecordDTO.value.homeBedApplyId = 63;
        callRecordDTO.value.homeBedApplyName = "严小香";
        // 发送请求
        callSave(callRecordDTO.value).then((res) => {
          console.log("【 被动呼叫保存记录-响应信息 】 = ", res);
          callId.value = res.callRecord.id;

        });

        const serviceInfo =
            (intent.serviceInfo && JSON.parse(intent.serviceInfo)) || {};

        intent.serviceInfo = serviceInfo;
        Object.assign(callInfo.value, intent);
        console.error("onIncomingCall", intent, callInfo.value);
        getHomeBedApply(serviceInfo.sn)
        form.value.imei = serviceInfo.sn;
        form.value.callTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
        form.value.callType = 1;
        form.value.callStatus = 0;
        incomingViewShow();
      },
      onAddConfereeStateChanged: (state) => {
        console.log("onAddConfereeStateChanged", state);
      },
      onCallReplaced: (replaced) => {
        console.log("onCallReplaced", replaced);
      },
      onCallStateChanged: (stateInfo) => {
        console.error(stateInfo, "stateInfo");
        if (stateInfo.state === duerRtcSdk.CallState.RINGBACK) {
          // 被叫开始响铃
          ringViewShow();
        } else if (stateInfo.state === duerRtcSdk.CallState.DISCONNECTED) {
          // 通话已经断开
          freeCallView();

          if (stateInfo.reason === duerRtcSdk.CallReason.TIMEOUT) {
            // 呼叫超时
            callTimeout();
          }
        } else if (stateInfo.state === duerRtcSdk.CallState.CONNECTED) {
          // 通话被正常接听
          callViewShow();
        }
        console.log("onCallStateChanged", stateInfo);
      },
      onConfereeLayout: (layouts) => {
        console.log("onConfereeLayout", layouts);
        setLayouts(layouts);
      },
      onRecordStateChanged: (recordStateInfo) => {
        console.log("onRecordStateChanged", recordStateInfo);
      },
    });

    // 设置链接监听器
    duerRtc.value.setConnectListener({
      onConnectionChanged: (conn) => {
        if (conn === 2) {
          // 长链接已建立
          console.log("建立连接了");
        }
        if (conn === 3) {
          // 长链接已断开
          duerRtc.value = null;
        }
        console.log("onConnectionChanged", conn);
      },
    });

    // 设置媒体监听器
    duerRtc.value.setMediaDeviceListener({
      // 麦克风/摄像头状态
      onMediaDeviceStateChanged: (device, state, error) => {
        console.error("onMediaDeviceStateChanged", device, state, error);
      },
    });
    rtcConnect(loginParams, duerRtc.value);
  }

  const rtcConnect = (loginParams, duerRtc) => {
    const { uid, appId } = loginParams;
    const uri = new duerRtcSdk.CallUri(uid, appId);
    loginParams.uri = uri;
    duerRtc.login(loginParams);
  }

  const handleLogin = (event) => {
    const loginParams = {
      // 从表单获取登录参数
      appId: "dc8ca706",
      uid: "13063863745",
      token: token.value,
      appName: "小度",
    };
    rtcListener(loginParams);
  }

  const rejectCall = () => {
    // handle call rejection logic here
    duerRtc.value.rejectIncomingCall(
        callInfo.value.index,
        "REJECT_CALL_USER_REASON",
    );
    duerRtc.value.logout();
    // duerRtc.value.rejectIncomingCall(intent.index, 'REJECT_CALL_USER_REASON');
    callView.value = false;
    callshowModel.value = true;
    showCall.value = false;
    // callSave(form.value);
    setTimeout(function () {
      handleLogin();
    }, 200000);
  }

  const answerCall = (mode) => {
    // handle call answering logic here
    duerRtc.value.answerCall(callInfo.value.index, mode, false);
    callInfo.value.callMode = mode;
    form.value.callStatus = 1;
    form.value.answerCallTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
  }
  const changeMode = () => {
    const mode =
        callInfo.value.callMode == duerRtcSdk.CallMode.AUDIO_VIDEO
            ? duerRtcSdk.CallMode.AUDIO_ONLY
            : duerRtcSdk.CallMode.AUDIO_VIDEO;

    if (mode == duerRtcSdk.CallMode.AUDIO_VIDEO) {
      console.error("视频");
      textMode.value = duerRtcSdk.CallMode.AUDIO_VIDEO;
      callMode.value = duerRtcSdk.CallMode.AUDIO_VIDEO;
      videoCallUrl.value =
          "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661515364706/audio000.png";
      videoCallText.value = "语音通话";
    } else if (mode == duerRtcSdk.CallMode.AUDIO_ONLY) {
      textMode.value = duerRtcSdk.CallMode.AUDIO_ONLY;
      callMode.value = duerRtcSdk.CallMode.AUDIO_ONLY;
      console.error("语音");

      videoCallUrl.value =
          "https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661828922567/videoCall0.png";
      videoCallText.value = "视频通话";
    }
    duerRtc.value.changeCallMode(mode);
    callInfo.value.callMode = mode;
  }

  /**
   * 挂断
   */
  const dropCall = () => {
    console.log("【 挂断电话 】");
    duerRtc.value.dropCall("DROP_CALL_USER_REASON");
    console.log("【 挂断电话,更新记录 】");
    // 挂断电话,更新记录
    callRecordDTO.value.id = callId.value;
    callRecordDTO.value.homeBedApplyId = 63;
    callRecordDTO.value.homeBedApplyName = "严小香";
    callRecordDTO.value.callType = 1;
    callRecordDTO.value.callStatus = 1;
    callRecordDTO.value.endCallTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    callRecordDTO.value.imei = imei.value;
    callRecordDTO.value.duration = calculateTimeDifference(answerCallTime.value, callRecordDTO.value.endCallTime);

    console.log("【 Drop call record dto 】 = ", callRecordDTO.value);
    // 发送更新请求
    callRecordUpdateAPI(callRecordDTO.value);
  }

  function calculateTimeDifference(startTime, endTime) {
    // 将时间字符串转换为Date对象
    const startDate = new Date(startTime.replace(/-/g, '/'));
    const endDate = new Date(endTime.replace(/-/g, '/'));

    // 计算两个时间之间的毫秒数
    const diffMs = endDate - startDate;

    // 计算总的秒数
    let totalSeconds = Math.floor(diffMs / 1000);

    // 计算小时、分钟和秒数
    const hours = Math.floor(totalSeconds / 3600);
    totalSeconds %= 3600;
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;

    // 构建时间差字符串
    let result = '';
    if (hours > 0) {
      result += `${hours}小时`;
    }
    if (minutes > 0) {
      result += `${minutes}分`;
    }
    if (seconds > 0 || result === '') {
      // 显示秒数或者保证至少显示 "0秒"
      result += `${seconds}秒`;
    }

    return result;
  }

  /**
   * 新增通话记录
   * @param data
   * @returns {Promise<void>}
   */
  async function callSave(data) {
    await callRecordSave(data).then((res) => {
      callId.value = res.callRecord.id;
      answerCallTime.value = res.callRecord.answerCallTime;
    });
    console.log("【 Call record id 】 = ", callId.value);
    console.log("【 Call record  answerCallTime 】 = ", answerCallTime.value);
    // form.value = {}
  }

  /**
   * 更新通话记录信息
   * @param data
   * @returns {Promise<void>}
   */
  async function callRecordUpdateAPI(data) {
    await callRecordUpdate(data).then(res => {
      console.log("【 接通电话，更新通话记录信息 】 = ", res);
    });

  }

  async function getToken() {
    let obj={
      appId: "dc8ca706",
      uid: "13063863745",
    }
    const data = await getTokenDueros(obj)
    token.value = data.token
    handleLogin();
  }

  async function getHomeBedApply(code){
    const data=await getHomeBedApplyId(code)
    form.value.homeBedApplyId=data.smartSpeak.homeBedApplyId
    callerName.value=data.smartSpeak.applyName
  }

  function isAgentBoole(){
    isAgent().then(res=>{
      if(res.isAgent==true){
        getToken()
      }
    })
  }
  isAgentBoole()
  const makeCall = (
      appId,
      uid,
      callMode,
      callerRole = duerRtcSdk.CallerRole.CALL_CENTER,
  ) => {
    const calleeUri = new duerRtcSdk.CallUri(uid, appId);
    const intent = duerRtcSdk.MakeCallIntent(
        calleeUri,
        duerRtcSdk.CallMode.AUDIO_VIDEO,
    );
    callMode && (intent.callMode = callMode);
    callerRole && (intent.callerRole = callerRole);
    callInfo.value.callMode = callMode;
    const result = duerRtc.value.makeCall(intent);
    form.value.homeBedApplyId = homeBedApplyId;
    form.value.callTime = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    form.value.callType = 0;
    form.value.callStatus = 0;
    form.value.imei = imei;
    //
    if (duerRtcSdk.CallReason.NORMAL == result) {
      // 呼出成功
    } else if (
        duerRtcSdk.CallReason.ALREADY_IN_CALL == result ||
        CallReason.EXCEPTION_INPUT_ILLEGAL == result
    ) {
      console.error("makeCall resaon", duerRtcSdk.CallReasonMap.get(result));
    } else {
      // 其他原因，目前不会出现
      console.warn("makeCall res", result);
    }
  };

  const emit = defineEmits(["hideDialog"]);

  // getToken()
  defineExpose({
    init
  });
</script>

<style scoped>
.usr-info {
  text-align: center;
}
.usr-pho {
  margin-top: 35px;
  width: 120px;
  height: 120px;
}
.usr-name {
  margin-top: 10px;
  font-weight: 500;
  font-size: 30px;
  line-height: 42px;
  color: #1a1a1a;
}
.incoming-call-tip {
  font-size: 16px;
  line-height: 22px;
  color: #666666;
}
.peer-info {
  text-align: center;
}
.op-btns {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  margin-top: 30px;
}
.op-btns img {
  width: 80px;
  height: 80px;
  margin: 16px 40px;
  cursor: pointer;
}
.op-txt {
  line-height: 20px;
  text-align: center;
}

.peer-pho {
  width: 104px;
  height: 104px;
  margin-top: 50px;
}
.peer-name {
  font-size: 60px;
  line-height: 86px;
  color: #ffffff;
}
.outing-call-tip {
  font-size: 42px;
  line-height: 60px;
  color: rgba(225, 225, 225, 0.5);
}

#call-view {
  position: relative;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 10052;
  background: #3c3667;
  color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  justify-content: center;
}

.main-view video {
  width: 100%;
  object-fit: fill;
}
.main-view .audio-name {
  margin-top: 100px;
  font-size: 62px;
  line-height: 87px;
}
.main-view .audio-call {
  font-size: 36px;
  line-height: 50px;
  color: rgba(225, 225, 225, 0.5);
  margin-top: 22px;
  margin-left: -70px;
}
.main-view .audio-tip-wrap {
  position: absolute;
  top: 0;
}

.sub-view {
  width: 280px;
  height: 162px;
  position: absolute;
  left: 48px;
  top: 48px;
  background-image: url("https://dumi-dueros-bj-tob.cdn.bcebos.com/amis/2022-8/1661773897681/audioBg.png");
  background-repeat: no-repeat;
  background-size: 100%;
  color: #fff;
  z-index: 1;
}
.sub-view video {
  width: 320px;
  height: 192px;
  object-fit: fill;
}
.sub-view .audio-tip-wrap {
  position: absolute;
  bottom: 10px;
  right: 10px;
}
.sub-view .audio-name {
  font-size: 40px;
  line-height: 67px;
  max-width: 300px;
}
.sub-view .audio-call {
  font-size: 24px;
  line-height: 34px;
  text-align: right;
}

.resize-handle {
  width: 10px;
  height: 10px;
  background: #fff;
  position: absolute;
  cursor: pointer;
}

.resize-handle.bottom-right {
  right: 0;
  bottom: 0;
  cursor: se-resize;
}

.resize-handle.bottom-left {
  left: 0;
  bottom: 0;
  cursor: sw-resize;
}

.resize-handle.top-right {
  right: 0;
  top: 0;
  cursor: ne-resize;
}

.resize-handle.top-left {
  left: 0;
  top: 0;
  cursor: nw-resize;
}
</style>
